<?php

class Membership_model extends CI_Model {

    function validate() {
        $this->db->where('username', $this->input->post('username'));
        $this->db->where('password', md5($this->input->post('password')));
        $query = $this->db->get('users');
        if ($query->num_rows == 1) {
            return true;
        }
    }

    function userInfo($username){
        $this->db->where('username', $username);
        $query = $this->db->get('users');
        $result = $query->result_array();
        return $result[0];
    }

    function create_member() {
        $new_member_insert_data = array(
            'email' => $this->input->post('email_address'),
            'username' => $this->input->post('username'),
            'password' => md5($this->input->post('password')),
            'role' => $this->input->post('role')
        );

        $insert = $this->db->insert('users', $new_member_insert_data);
        return $insert;
    }

    function member_already_exists($exceptionsArray = array()) {
        $this->db->where('username', $this->input->post('username'));
        $query = $this->db->get('users');

        if ($query->num_rows > 0){
            $result = $query->result_array();
            foreach($result as $row){
                if(!in_array($row['id'], $exceptionsArray)) return true;
            }
        }
        return false;
    }

    function email_already_registered($exceptionsArray = array()) {
        $this->db->where('email', $this->input->post('email_address'));
        $query = $this->db->get('users');

        if ($query->num_rows > 0){
            $result = $query->result_array();
            foreach($result as $row){
                if(!in_array($row['id'], $exceptionsArray)) return true;
            }
        }
        return false;
    }

    function user_id($username) {
        $this->db->where('username', $username);
        $query = $this->db->get('users');

        if ($query->num_rows > 0){
            $result = $query->result_array();
            return $result[0]['id'];
        }
        return false;
    }

    function change_user_info($id, $username, $email, $password, $role = -1){
        $data = array(
           'username' => $username,
           'password ' => md5($password),
           'email' => $email,
           'role' => $role
        );
        if($role >= 0){
            $data['role'] = $role;
        }
        $this->db->where('id', $id);
        $this->db->update('users', $data);
    }

}